package com.nashuju.web.controller.user;

import java.util.List;
import java.util.Map;

import org.durcframework.core.JsonObjProcessor;
import org.durcframework.core.UserContext;
import org.durcframework.core.controller.CrudController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.nashuju.web.entity.role.Role;
import com.nashuju.web.entity.user.User;
import com.nashuju.web.entity.user.UserSch;
import com.nashuju.web.service.role.RoleService;
import com.nashuju.web.service.user.UserService;
import com.nashuju.web.util.PasswordUtil;

@Controller
public class UserController extends CrudController<User, UserService> {

    @Autowired
    private RoleService roleService;


    @RequestMapping("/addRUser.do")
    public @ResponseBody Object addRUser(User entity) {
        String password = entity.getPassword(); // md5加密后的
        password = PasswordUtil.createHash(password);
        entity.setPassword(password);
        return this.save(entity);
    }

    @RequestMapping("/listRUser.do")
    public @ResponseBody Object listRUser(UserSch searchEntity) {
        return this.queryWithProcessor(searchEntity, new JsonObjProcessor<User>() {
            @Override
            public void process(User entity, Map<String, Object> jsonObject) {
                List<Role> userRoles = roleService.getUserRole(entity.getUsername());

                jsonObject.put("roles", userRoles);
            }
        });
    }

    @RequestMapping("/updateRUser.do")
    public @ResponseBody Object updateRUser(User enity) {
        return this.update(enity);
    }

    @RequestMapping("/delRUser.do")
    public @ResponseBody Object delRUser(User enity) {
        return this.delete(enity);
    }

    @RequestMapping("/resetUserPassword.do")
    public @ResponseBody Object resetUserPassword(User user) {
        String newPwsd = this.getService().resetUserPassword(user);
        return success(newPwsd);
    }

    @RequestMapping("/updateUserPassword.do")
    public @ResponseBody Object updateUserPassword(String oldPswd, String newPswd, String newPswd2) {

        if (!newPswd.equals(newPswd2)) {
            return error("两次输入的新密码不一样");
        }
        User user = UserContext.getInstance().getUser();
        User storeUser = this.getService().get(user.getUsername());

        boolean isPswdCorrect = PasswordUtil.validatePassword(oldPswd, storeUser.getPassword());

        if (!isPswdCorrect) {
            return error("原密码输入有误");
        }

        this.getService().updateUserPassword(storeUser, newPswd);

        return success();
    }

}
